package com.netsdk.demo.customize;

import static com.netsdk.lib.Utils.getOsPrefix;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;

import com.netsdk.demo.util.CaseMenu;
import com.netsdk.lib.NetSDKLib;
import com.netsdk.lib.ToolKits;
import com.netsdk.lib.NetSDKLib.EM_VIDEO_TALK_LOG_CALLTYPE;
import com.netsdk.lib.NetSDKLib.EM_VIDEO_TALK_LOG_ENDSTATE;
import com.netsdk.lib.NetSDKLib.NET_RECORD_VIDEO_TALK_LOG;
import com.netsdk.lib.callback.impl.DefaultDisconnectCallback;
import com.netsdk.lib.callback.impl.DefaultHaveReconnectCallBack;
import com.netsdk.lib.enumeration.EM_NEW_CONFIG;
import com.netsdk.lib.structure.CFG_PSTN_PERSON_SERVER_INFO;
import com.netsdk.lib.structure.CFG_PSTN_PERSON_SERVER_INFO_ALL;
import com.sun.jna.Memory;

public class PSTNPersonServerDemo {
	// SDk对象初始化
	public static final NetSDKLib netsdk = NetSDKLib.NETSDK_INSTANCE;
	public static final NetSDKLib configsdk = NetSDKLib.CONFIG_INSTANCE;

	// 判断是否初始化
	private static boolean bInit = false;
	// 判断log是否打开
	private static boolean bLogOpen = false;
	// 设备信息
	private NetSDKLib.NET_DEVICEINFO_Ex deviceInfo = new NetSDKLib.NET_DEVICEINFO_Ex();
	// 登录句柄
	private NetSDKLib.LLong m_hLoginHandle = new NetSDKLib.LLong(0);

	// 智能事件订阅句柄
	private NetSDKLib.LLong m_attachHandle = new NetSDKLib.LLong(0);

	// 回调函数需要是静态的，防止被系统回收
	// 断线回调
	private static NetSDKLib.fDisConnect disConnectCB = DefaultDisconnectCallback.getINSTANCE();
	// 重连回调
	private static NetSDKLib.fHaveReConnect haveReConnectCB = DefaultHaveReconnectCallBack.getINSTANCE();

	// 编码格式
	public static String encode;

	static {
		String osPrefix = getOsPrefix();
		if (osPrefix.toLowerCase().startsWith("win32-amd64")) {
			encode = "GBK";
		} else if (osPrefix.toLowerCase().startsWith("linux-amd64")) {
			encode = "UTF-8";
		}
	}

	/**
	 * 获取当前时间
	 */
	public static String GetDate() {
		SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return simpleDate.format(new java.util.Date()).replaceAll("[^0-9]", "-");
	}

	/**
	 * 初始化SDK库
	 */
	public static boolean Init() {
		bInit = netsdk.CLIENT_Init(disConnectCB, null);// 进程启动时，初始化一次
		if (!bInit) {
			System.out.println("Initialize SDK failed");
			return false;
		}
		// 配置日志
		PSTNPersonServerDemo.enableLog();

		// 设置断线重连回调接口, 此操作为可选操作，但建议用户进行设置
		netsdk.CLIENT_SetAutoReconnect(haveReConnectCB, null);

		// 设置登录超时时间和尝试次数，可选
		// 登录请求响应超时时间设置为3S
		int waitTime = 3000;
		// 登录时尝试建立链接 1 次
		int tryTimes = 1;
		netsdk.CLIENT_SetConnectTime(waitTime, tryTimes);
		// 设置更多网络参数， NET_PARAM 的nWaittime ， nConnectTryNum 成员与 CLIENT_SetConnectTime
		// 接口设置的登录设备超时时间和尝试次数意义相同,可选
		NetSDKLib.NET_PARAM netParam = new NetSDKLib.NET_PARAM();
		// 登录时尝试建立链接的超时时间
		netParam.nConnectTime = 10000;
		// 设置子连接的超时时间
		netParam.nGetConnInfoTime = 3000;
		netsdk.CLIENT_SetNetworkParam(netParam);
		return true;
	}

	/**
	 * 打开 sdk log
	 */
	private static void enableLog() {
		NetSDKLib.LOG_SET_PRINT_INFO setLog = new NetSDKLib.LOG_SET_PRINT_INFO();
		File path = new File("sdklog/");
		if (!path.exists())
			path.mkdir();

		// 这里的log保存地址依据实际情况自己调整
		String logPath = path.getAbsoluteFile().getParent() + "\\sdklog\\" + "sdklog" + GetDate() + ".log";
		setLog.nPrintStrategy = 0;
		setLog.bSetFilePath = 1;
		System.arraycopy(logPath.getBytes(), 0, setLog.szLogFilePath, 0, logPath.getBytes().length);
		System.out.println(logPath);
		setLog.bSetPrintStrategy = 1;
		bLogOpen = netsdk.CLIENT_LogOpen(setLog);
		if (!bLogOpen)
			System.err.println("Failed to open NetSDK log");
	}

	/**
	 * 高安全登录
	 */
	public void loginWithHighLevel() {
		// 输入结构体参数
		NetSDKLib.NET_IN_LOGIN_WITH_HIGHLEVEL_SECURITY pstlnParam = new NetSDKLib.NET_IN_LOGIN_WITH_HIGHLEVEL_SECURITY() {
			{
				szIP = m_strIpAddr.getBytes();
				nPort = m_nPort;
				szUserName = m_strUser.getBytes();
				szPassword = m_strPassword.getBytes();
			}
		};
		// 输出结构体参数
		NetSDKLib.NET_OUT_LOGIN_WITH_HIGHLEVEL_SECURITY pstOutParam = new NetSDKLib.NET_OUT_LOGIN_WITH_HIGHLEVEL_SECURITY();

		// 写入sdk
		m_hLoginHandle = netsdk.CLIENT_LoginWithHighLevelSecurity(pstlnParam, pstOutParam);
		if (m_hLoginHandle.longValue() == 0) {
			System.err.printf("Login Device[%s] Port[%d]Failed. %s\n", m_strIpAddr, m_nPort,
					netsdk.CLIENT_GetLastError());
		} else {
			deviceInfo = pstOutParam.stuDeviceInfo; // 获取设备信息
			System.out.println("Login Success");
			System.out.println("Device Address：" + m_strIpAddr);
			System.out.println("设备包含：" + deviceInfo.byChanNum + "个通道");
		}
	}

	/**
	 * 退出
	 */
	public void logOut() {
		if (m_hLoginHandle.longValue() != 0) {
			netsdk.CLIENT_Logout(m_hLoginHandle);
			System.out.println("LogOut Success");
		}
	}

	/**
	 * 清理sdk环境并退出
	 */
	public static void cleanAndExit() {
		if (bLogOpen) {
			netsdk.CLIENT_LogClose(); // 关闭sdk日志打印
		}
		netsdk.CLIENT_Cleanup(); // 进程关闭时，调用一次
		System.exit(0);
	}

	/**
	 * 查询通话记录
	 */
	public void queryVideoTalkLog() {
		NetSDKLib.FIND_RECORD_VIDEO_TALK_LOG_CONDITION stuQueryCondition = new NetSDKLib.FIND_RECORD_VIDEO_TALK_LOG_CONDITION();
		stuQueryCondition.bCallTypeEnable = 1; // 呼叫类型查询条件有效
		stuQueryCondition.nCallTypeListNum = 2; // 呼叫类型有效枚举个数
		stuQueryCondition.emCallTypeList[0] = EM_VIDEO_TALK_LOG_CALLTYPE.EM_VIDEO_TALK_LOG_CALLTYPE_INCOMING;
		stuQueryCondition.emCallTypeList[1] = EM_VIDEO_TALK_LOG_CALLTYPE.EM_VIDEO_TALK_LOG_CALLTYPE_OUTGOING;
		stuQueryCondition.bEndStateEnable = 1; // 最终状态查询条件有效
		stuQueryCondition.nEndStateListNum = 2; // 最终状态有效枚举个数
		stuQueryCondition.emEndStateList[0] = EM_VIDEO_TALK_LOG_ENDSTATE.EM_VIDEO_TALK_LOG_ENDSTATE_MISSED;
		stuQueryCondition.emEndStateList[1] = EM_VIDEO_TALK_LOG_ENDSTATE.EM_VIDEO_TALK_LOG_ENDSTATE_RECEIVED;

		NetSDKLib.NET_IN_FIND_RECORD_PARAM stuFindInParam = new NetSDKLib.NET_IN_FIND_RECORD_PARAM();
		stuFindInParam.emType = NetSDKLib.EM_NET_RECORD_TYPE.NET_RECORD_VIDEOTALKLOG;
		stuFindInParam.pQueryCondition = stuQueryCondition.getPointer();

		NetSDKLib.NET_OUT_FIND_RECORD_PARAM stuFindOutParam = new NetSDKLib.NET_OUT_FIND_RECORD_PARAM();

		stuQueryCondition.write();
		if (netsdk.CLIENT_FindRecord(m_hLoginHandle, stuFindInParam, stuFindOutParam, 5000)) { // 按查询条件查询记录
			System.out.println("FindRecord Succeed" + "\n" + "FindHandle :" + stuFindOutParam.lFindeHandle);

			int nRecordCount = 10;
			NetSDKLib.NET_IN_FIND_NEXT_RECORD_PARAM stuFindNextInParam = new NetSDKLib.NET_IN_FIND_NEXT_RECORD_PARAM();
			stuFindNextInParam.lFindeHandle = stuFindOutParam.lFindeHandle;
			stuFindNextInParam.nFileCount = nRecordCount; // 想查询的记录条数

			NET_RECORD_VIDEO_TALK_LOG[] stuRecord = new NET_RECORD_VIDEO_TALK_LOG[nRecordCount];
			for (int i = 0; i < nRecordCount; i++) {
				stuRecord[i] = new NET_RECORD_VIDEO_TALK_LOG();
			}

			NetSDKLib.NET_OUT_FIND_NEXT_RECORD_PARAM stuFindNextOutParam = new NetSDKLib.NET_OUT_FIND_NEXT_RECORD_PARAM();
			stuFindNextOutParam.nMaxRecordNum = nRecordCount;
			stuFindNextOutParam.pRecordList = new Memory(stuRecord[0].size() * nRecordCount);
			stuFindNextOutParam.pRecordList.clear(stuRecord[0].size() * nRecordCount);
			ToolKits.SetStructArrToPointerData(stuRecord, stuFindNextOutParam.pRecordList); // 将数组内存拷贝到Pointer
			boolean zRet = netsdk.CLIENT_FindNextRecord(stuFindNextInParam, stuFindNextOutParam, 5000);
			if (zRet) {
				ToolKits.GetPointerDataToStructArr(stuFindNextOutParam.pRecordList, stuRecord);
				System.out.println("nRetRecordNum " + stuFindNextOutParam.nRetRecordNum);
				for (int i = 0; i < stuFindNextOutParam.nRetRecordNum; ++i) {
					System.out.println();
					PrintStruct.print(stuRecord[i]);
				}
			} else {
				System.err.println("FindNextRecord Failed!" + ToolKits.getErrorCode());
			}

			netsdk.CLIENT_FindRecordClose(stuFindOutParam.lFindeHandle);
		} else {
			System.err.println("FindRecord Failed!" + ToolKits.getErrorCode());
		}
	}

	/**
	 * 获取报警能力集
	 */
//	public void getCapAlarm() {
//		int channel = 0;// 通道号
//		CFG_CAP_ALARM_INFO info = new CFG_CAP_ALARM_INFO();
//		String command = EM_NEW_QUERY_SYSTEM_INFO.CFG_CAP_ALARM.getValue();
//		byte[] data = new byte[info.size()];
//		boolean result = netsdk.CLIENT_QueryNewSystemInfo(m_hLoginHandle, command, channel, data, data.length,
//				new IntByReference(0), 5000);
//		if (!result) {
//			System.err.println("CLIENT_QueryNewSystemInfo failed:" + ToolKits.getErrorCode());
//		}
//		String str = new String(data);
//		JSONObject obj = JSON.parseObject(str);
//		System.out.println("obj:" + obj);
//
//		info.write();
//		result = configsdk.CLIENT_ParseData(command, data, info.getPointer(), info.size(), null);
//		if (!result) {
//			System.err.println("CLIENT_ParseData failed:" + ToolKits.getErrorCode());
//		}
//		info.read();
//		System.out.println("最大电话报警中心数: " + info.nMaxPSTNAlarmServer);
//	}

	/**
	 * 个人电话接机配置
	 */
	public void setPSTNPersonServer() {
		int channel = 0;// 通道号
		String command = EM_NEW_CONFIG.CFG_CMD_PSTN_PERSON_SERVER.getValue();
		CFG_PSTN_PERSON_SERVER_INFO_ALL info = new CFG_PSTN_PERSON_SERVER_INFO_ALL();
		// 获取
		if (ToolKits.GetDevConfig(m_hLoginHandle, channel, command, info)) {
			System.out.println("个人电话接机配置使能: " + info.bEnable);
			System.out.println("有效的个人电话接机配置信息个数,目前最多支持3个: " + info.nServerCount);
			CFG_PSTN_PERSON_SERVER_INFO[] stuPSTNPersonServer = info.stuPSTNPersonServer;
			try {
				for (int i = 0; i < info.nServerCount; i++) {
					System.out.println("-----------第" + (i + 1) + "个电话接机配置信息----------");
					System.out.println("个人电话名称: " + new String(stuPSTNPersonServer[i].szName, encode));
					System.out.println("个人电话接收机号码: " + new String(stuPSTNPersonServer[i].szNumber, encode));
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			// 设置，在获取的基础上设置
			if (ToolKits.SetDevConfig(m_hLoginHandle, channel, command, info)) {
				System.out.println("Set CFG_CMD_PSTN_PERSON_SERVER Succeed!");
			} else {
				System.err.println("Set CFG_CMD_PSTN_PERSON_SERVER Failed!" + netsdk.CLIENT_GetLastError());
			}

		} else {
			System.err.println("Get CFG_CMD_PSTN_PERSON_SERVER Failed!" + netsdk.CLIENT_GetLastError());
		}
	}

	/******************************** 测试控制台 ***************************************/

	// 配置登陆地址，端口，用户名，密码
	private String m_strIpAddr = "10.55.61.227";
	private int m_nPort = 37777;
	private String m_strUser = "admin";
	private String m_strPassword = "admin123";

	public static void main(String[] args) {
		PSTNPersonServerDemo demo = new PSTNPersonServerDemo();
		demo.InitTest();
		demo.RunTest();
		demo.EndTest();

	}

	/**
	 * 初始化测试
	 */
	public void InitTest() {
		PSTNPersonServerDemo.Init();
		this.loginWithHighLevel();
	}

	/**
	 * 加载测试内容
	 */
	public void RunTest() {
		CaseMenu menu = new CaseMenu();
		// 电话薄协议
		//menu.addItem(new CaseMenu.Item(this, "获取报警能力集", "getCapAlarm"));
		menu.addItem(new CaseMenu.Item(this, "个人电话接机配置", "setPSTNPersonServer"));

		// 通话记录协议
		menu.addItem(new CaseMenu.Item(this, "通话记录协议", "queryVideoTalkLog"));
		menu.run();
	}

	/**
	 * 结束测试
	 */
	public void EndTest() {
		System.out.println("End Test");
		this.logOut(); // 登出设备
		System.out.println("See You...");
		PSTNPersonServerDemo.cleanAndExit(); // 清理资源并退出
	}

}
